package middleware

import (
	"context"
	"net/http"

	"github.com/yourusername/apijson-auth/database"
	"github.com/yourusername/apijson-auth/model"
)

type APIJSONVerifier struct{}

func (v *APIJSONVerifier) Verify(table, method string, userRole int) bool {
	var access model.Access
	query := "SELECT * FROM Access WHERE name = ?"
	err := database.DB.QueryRow(query, table).Scan(
		&access.ID, &access.Debug, &access.Name, &access.Alias,
		&access.Get, &access.Head, &access.Gets, &access.Post,
		&access.Put, &access.Delete)
	if err != nil {
		return false
	}

	var requiredRoleStr string
	switch method {
	case "GET":
		requiredRoleStr = access.Get
	case "HEAD":
		requiredRoleStr = access.Head
	case "GETS":
		requiredRoleStr = access.Gets
	case "POST":
		requiredRoleStr = access.Post
	case "PUT":
		requiredRoleStr = access.Put
	case "DELETE":
		requiredRoleStr = access.Delete
	default:
		return false
	}

	requiredRole := roleStringToInt(requiredRoleStr)
	return userRole >= requiredRole
}

func roleStringToInt(role string) int {
	switch role {
	case "UNKNOWN":
		return model.UNKNOWN
	case "LOGIN":
		return model.LOGIN
	case "CONTACT":
		return model.CONTACT
	case "CIRCLE":
		return model.CIRCLE
	case "OWNER":
		return model.OWNER
	case "ADMIN":
		return model.ADMIN
	default:
		return model.UNKNOWN
	}
}

func AuthMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		token := r.Header.Get("Authorization")
		if token == "" {
			http.Error(w, "Unauthorized", http.StatusUnauthorized)
			return
		}

		// 这里应该验证token并获取用户信息
		// 简化示例，直接设置一个测试用户
		user := model.User{
			ID:    1,
			Name:  "testuser",
			Role:  model.LOGIN,
			Token: token,
		}

		// 将用户信息存入上下文
		ctx := context.WithValue(r.Context(), "user", user)
		next.ServeHTTP(w, r.WithContext(ctx))
	})
}
